<template>
  <div style="height:100%;width:100%;position:relative;">
      <div class="pagetop">
          <div class="search-title">快速查询</div>
          <el-input v-model="txtsearch" placeholder="仪器代号|名称|助记符" style="width:200px"></el-input>
          <div class="search-title">工作组：</div>
          <span style="width: 80px;margin-right: 5px;">
              <el-select v-model="defid" placeholder="请选择" style="width:130px;" @change="QueryData">
                  <el-option v-for="item in glist" :key="item.labgroupid" :label="item.labgroupname" :value="item.labgroupid"></el-option>
              </el-select>
          </span>
          <div class="top-deal">
              <el-button @click="QueryData" icon="el-icon-search" type="primary" v-has="'PINQUERY'" :disabled="changeflag">查询</el-button>
              <el-button @click="btnAdd" icon="el-icon-plus" v-has="'PADD'">新增</el-button>
              <el-button @click="btnDelete" icon="el-icon-delete" v-has="'PDELETE'">删除</el-button>
              <el-button @click="btnSave" icon="el-icon-document" v-has="'PMODIFY'" :disabled="!changeflag">保存</el-button>
              <el-button @click="btnClear" icon="el-icon-printer" :disabled="!changeflag">取消</el-button>
              <el-button @click="btnExport" icon="el-icon-upload2">导出</el-button>
              <!-- <el-button @click="btnPrint" icon="el-icon-printer" :disabled="changeflag">打印</el-button> -->
          </div>
      </div>
      <div class="pagecenter">
          <div class="middle-center">
              <vxe-table :data="list" :loading="loading" :keyboard-config="keyConfig" :row-class-name="rowClassName" :select-config="selectConfig" :sort-config="{trigger: 'cell'}" :edit-config="{trigger: 'click', mode: 'cell',showStatus: true,activeMethod:activeMethod,showIcon:false}" class="mytablestyle" @current-change="currentChangeEvent" border fit height="auto" header-align="center" header-alin="center" highlight-current-row highlight-hover-row highlight-hover-column ref="xTable" resizable @edit-closed="EditChange" show-header-overflow="tooltip" show-overflow="tooltip" size="mini" stripe :edit-rules="instrmentvalidRules">
                  <vxe-table-column type="index" title="NO." width="45" align="center"></vxe-table-column>
                  <vxe-table-column field="instrno" title="仪器代码" width="85" :edit-render="{name:'input', autoselect: true,events: {change: hasChange}}"></vxe-table-column>
                  <vxe-table-column field="instrname" title="仪器名称" width="105" :edit-render="{name:'input', autoselect: true,events: {change: hasChange}}"></vxe-table-column>
                  <vxe-table-column field="instrkind" title="仪器类别" width="75" :edit-render="{name:'select', options: $opt.InstrKind,events: {click: hasChange}}">
                      <!-- <template v-slot="{row}">
                          <el-select v-model="row.instrkind" filterable clearable>
                              <el-option v-for="(item,index) in $opt.InstrKind" :label="item.label" :value="item.value" :key="index"></el-option>
                          </el-select>
                      </template> -->
                  </vxe-table-column>
                  <vxe-table-column field="inputno" title="快速输入码" width="90" :edit-render="{name:'input', autoselect: true,events: {change: hasChange}}"></vxe-table-column>
                  <vxe-table-column field="inputcode" title="助记符" width="90" :edit-render="{name:'input', autoselect: true,events: {change: hasChange}}"></vxe-table-column>
                  <vxe-table-column field="seq" title="序号" width="60" :edit-render="{name:'input', autoselect: true,events: {change: hasChange}}" align="center">
                  </vxe-table-column>
                  <vxe-table-column field="instrid" title="对应LIS仪器(双击开窗)" width="200">
                      <template v-slot="{row}">
                          <rm-ddl-instrument v-model="row.instrid" :labgroupid="defid" width="100%" :clearable="false"></rm-ddl-instrument>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="warehouse" title="培养仓列表(逗号,分隔)" width="155" :edit-render="{name:'input', autoselect: true}"></vxe-table-column>
                  <vxe-table-column field="rows" title="行数" width="55" :edit-render="{name:'input', autoselect: true,events: {change: hasChange}}" align="center">
                  </vxe-table-column>
                  <vxe-table-column field="columns" title="列数" width="55" :edit-render="{name:'input', autoselect: true,events: {change: hasChange}}" align="center">
                  </vxe-table-column>
              </vxe-table>
          </div>
      </div>
  </div>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils";
import XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
  name: "LIS842",
  data() {
      return {
          keyConfig: {
              isDel: true,
              isTab: true,
              isEdit: true,
              isArrow: true,
          },
          keyLocalConfig: {
              isArrow: true,
          },
          selectConfig: { tigger: "row" },
          txtsearch: "",
          tableColumn: [],
          tableData: [],
          buttonwidth: 0,
          loading: false,
          changeflag: false,
          isFirstLoading: false,
          tempindex: 0,
          curselectrow: "",
          instrmentvalidRules: { instrno: [{ required: true, message: "必须填写仪器代码" }], instrid: [{ required: true, message: "必须选择对应LIS仪器" }] },
          defid: "",
          glist: [],
      };
  },
  mounted() {
      this.InitPage();
  },
  updated() {
      if (this.isFirstLoading) {
          let currentrow = "";
          if (this.curselectrow != "") {
              //新增，修改，删除
              currentrow = this.tableData.filter((item) => item.instrno == this.curselectrow.instrno)[0];
          } else {
              //查询
              this.curselectrow = this.$refs.xTable.getData(0);
              currentrow = this.curselectrow;
          }
          this.$nextTick(() => {
              if (currentrow) {
                  this.isFirstLoading = false;
                  this.changeflag = false;
                  this.$refs.xTable.setCurrentRow(currentrow);
              }
          });
      }
  },
  watch: {
      txtsearch(val) {
          var row = this.$refs.xTable.getCurrentRow();
          if (this.$refs.xTable.tableData.length > 0) row = this.$refs.xTable.tableData[0];
          if (row) {
              this.$refs.xTable.setCurrentRow(row);
          }
      },
  },
  computed: {
      list() {
          let filterName = this.txtsearch.trim();
          if (filterName) {
              let rest = this.tableData.filter((item) => {
                  return item.instrno.toUpperCase().indexOf(filterName.toUpperCase()) > -1 || (item.inputcode ? item.inputcode.toUpperCase().indexOf(filterName.toUpperCase()) > -1 : false) || (item.instrname ? item.instrname.toUpperCase().indexOf(filterName.toUpperCase()) > -1 : false);
              });
              return rest;
          } else {
              return this.tableData;
          }
      },
  },
  methods: {
      InitPage() {
          this.$tool
              .request({
                  url: "LIS/LIS8/LIS842",
                  method: "post",
                  data: {
                      action: "InitPage",
                      labgroupid: this.defid,
                  },
              })
              .then((res) => {
                  this.defid = res.defid;
                  this.glist = res.glist;
                  this.QueryData(); //初始化主列表
              })
              .catch((err) => {});
      },
      QueryData() {
          this.loading = true;
          this.$tool
              .request({
                  url: "LIS/LIS8/LIS842",
                  method: "post",
                  data: {
                      action: "QueryData",
                      labgroupid: this.defid,
                  },
              })
              .then((res) => {
                  this.tableData = res.data;
                  this.isFirstLoading = true;
                  // if (res.data.length > 0) {
                  //     this.$refs.xTable.setCurrentRow(res.data[0]);
                  // } else {
                  //     this.$refs.xTable.setCurrentRow(null);
                  // }
                  this.loading = false;
              })
              .catch((err) => {
                  this.loading = false;
              });
      },
      activeMethod({ row }) {
          return true;
      },
      rowClassName({ row, rowIndex }) {
          let isDirty = this.$refs.xTable.hasRowChange(row);
          if (isDirty) {
              this.changeflag = true;
              return "row-modify";
          }
          if (this.$refs.xTable.hasRowInsert(row)) {
              this.changeflag = true;
              return "row-new";
          }
      },
      querySearch(queryString, cb) {
          var restaurants = this.$opt.InstrKind;
          var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
          // 调用 callback 返回建议列表的数据
          cb(results);
      },
      createFilter(queryString) {
          return (restaurant) => {
              return restaurant.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
          };
      },
      currentChangeEvent({ row }) {
          this.curselectrow = row;
      },
      btnAdd() {
          var seq = this.$refs.xTable.tableData.length;
          var seqk = (seq + 1) * 10;
          let row = {
              instrno: "",
              instrname: "",
              instrkind: "",
              inputcode: "",
              seq: seqk,
              instrid: null,
              inputno: "",
              warehouse: "",
              rows: "",
              columns: "",
          };
          this.$refs.xTable.insert(row).then(({ row }) => {
              this.$refs.xTable.setCurrentRow(row);
              this.$refs.xTable.setActiveRow(row);
              this.curselectrow = row;
          });
      },
      btnDelete() {
          this.$confirm("您确定要删除这条数据吗？", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
          })
              .then(() => {
                  try {
                      this.changeflag = true;
                      var delrow = this.$refs.xTable.getCurrentRow();
                      if (delrow) {
                          var alld = this.$refs.xTable.tableData;
                          var rowindex = alld.indexOf(delrow);
                          this.$refs.xTable.remove(delrow);
                          let havedata = this.$refs.xTable.tableData;
                          if (havedata.length > 0) {
                              if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                              let selectrow = havedata[rowindex];
                              this.$refs.xTable.setCurrentRow(selectrow);
                              this.curselectrow = selectrow;
                          }
                      }
                  } catch (e) {
                      console.log("error", e);
                  }
              })
              .catch(() => {});
      },
      btnSave() {
          this.$refs.xTable.validate((valid, callback) => {
              if (valid) {
                  this.savedata();
              } else {
                  let msgList = [];
                  Object.values(callback).forEach(params => {
                      let {rowIndex, column, rules} = params;
                      rules.forEach(rule => {
                          msgList.push(`第 ${rowIndex + 1} 行 "${column.title}" 字段，校验错误：${rule.message}`);
                      });
                  });
                  if (msgList.length > 0) {
                      let alerthtml = ``;
                      msgList.forEach(element => {
                          alerthtml += `<div>${element}</div>`;
                      });
                      this.$alert(alerthtml, '提示', {
                          dangerouslyUseHTMLString: true,
                      });
                  }
              }
          });
      },
      async savedata() {
          let xTableData = this.$refs.xTable.getRecordset();
          try {
              const res = await this.$tool.request({
                  url: "LIS/LIS8/LIS842",
                  method: "post",
                  data: {
                      action: "savedata",
                      urec: xTableData,
                  },
              });
              if (res.errcode == "1") {
                  this.$message.success("操作成功！");
                  this.QueryData();
              } else {
                  this.$message.error("操作失败！" + res.errmsg);
              }
          } catch (e) {
              this.$alert(e);
          }
      },
      btnExport() {
          let data = this.getExportData();
          let book = XLSX.utils.book_new();
          let sheet = XLSX.utils.json_to_sheet(data, { skipHeader: true });
          XLSX.utils.book_append_sheet(book, sheet);
          let wbout = XLSX.write(book, { bookType: "xlsx", bookSST: false, type: "binary" });
          let blob = new Blob([this.toBuffer(wbout)], { type: "application/octet-stream" });
          // 保存导出
          FileSaver.saveAs(blob, "细菌相关仪器.xlsx");
      },
      getExportData() {
          if (this.tableColumn.length == 0) {
              let columns = this.$refs.xTable.getColumns();
              columns.forEach((item) => {
                  this.tableColumn.push({ title: item.title, field: item.property });
              });
          }
          let datas = this.tableData;
          let columns = this.tableColumn.filter((item) => item.field);
          let headers = [columns.map((item) => item.title)];
          return headers.concat(
              datas.map((row) => {
                  return columns.map((column) => {
                      return row[column.field];
                  });
              })
          );
      },
      toBuffer(wbout) {
          let buf = new ArrayBuffer(wbout.length);
          let view = new Uint8Array(buf);
          for (let index = 0; index !== wbout.length; ++index) view[index] = wbout.charCodeAt(index) & 0xff;
          return buf;
      },
      btnClear() {
          this.$confirm("您确定要取消这次改动吗？", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
          })
              .then(() => {
                  this.isFirstLoading = true;
                  this.QueryData();
              })
              .catch(() => {});
      },
      btnPrint() {},
      EditChange({ row, column }) {
          if (column.property == "instrname") {
              row.inputcode = this.$pub.CreateInputcode(row.instrname, this, 20);
          }
      },
      hasChange() {
          this.changeflag = true;
      },
  },
};
</Script>

<style scoped>
.pagetop {
  width: 100%;
  height: 35px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
  z-index: 99;
}

.pagecenter {
  position: absolute;
  top: 40px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}

.middle-center {
  position: absolute;
  height: 100%;
  left: 0px;
  right: 0px;
  overflow: auto;
}

.table1style tr td {
  padding: 0px 2px 0px 2px;
}

/deep/ .el-button.is-disabled {
  border: 0px;
  color: grey;
  background-color: #e6e6e6;
  font-weight: normal;
}
.search-title {
  margin: 0 5px 0 20px;
  font-size: 12px;
}
.top-deal {
  right: 5px;
  position: absolute;
  top: 5px;
  display: flex;
  align-items: center;
}
/deep/ tr.vxe-body--row.row-modify {
  color: blue;
}
/deep/ tr.vxe-body--row.row-new {
  color: #cc6600;
}
/deep/.mytablestyle tr td div .el-input__inner {
  border: 1px solid rgba(255, 254, 254, 0) !important;
  background-color: rgba(255, 254, 254, 0) !important;
}
</style>